#define  _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"

void SeqListInit(SeqList* ps)
{
	assert(ps);

	ps->_a = NULL;
	ps->_capacity = ps->_size = 0;
}

void SeqListDestory(SeqList* ps)
{
	assert(ps);

	free(ps->_a);
	ps->_a = NULL;
	ps->_size = ps->_capacity = 0;
}

void SeqListCheckCapacity(SeqList* ps)
{
	if (ps->_capacity == ps->_size)
	{
		int newcapacity = ps->_capacity == 0 ? 4 : 2 * ps->_capacity;
		SLDataType* p = (SLDataType*)realloc(ps->_a, sizeof(SLDataType) * newcapacity);
		if (!p)
		{
			perror("SeqListCheckCapacity");
			exit(-1);
		}
		ps->_a = p;
		ps->_capacity = newcapacity;
	}
}

void SeqListPrint(SeqList* ps)
{
	assert(ps);
	for (int i = 0; i < ps->_size; i++)
	{
		printf("%d  ", ps->_a[i]);
	}
	printf("\n");
}

void SeqListInsert(SeqList* ps, int pos, SLDataType x)
{
	assert(ps);
	SeqListCheckCapacity(ps);
	for (int i = ps->_size - 1; i >= pos; i--)
	{
		ps->_a[i + 1] = ps->_a[i];
	}
	ps->_a[pos] = x;
	ps->_size++;
}

void SeqListErase(SeqList* ps, int pos)
{
	assert(ps);
	assert(ps->_size > 0);

	for (int i = pos; i < ps->_size - 1; i++)
	{
		ps->_a[i] = ps->_a[i + 1];
	}
	ps->_size--;
}

void SeqListPushBack(SeqList* ps, SLDataType x)
{
	assert(ps);

	SeqListCheckCapacity(ps);
	ps->_a[ps->_size++] = x;
}

void SeqListPushFront(SeqList* ps, SLDataType x)
{
	SeqListInsert(ps, 0, x);
}

void SeqListPopFront(SeqList* ps)
{
	SeqListErase(ps, 0);
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps);
	assert(ps->_size > 0);

	ps->_size--;
}

int SeqListFind(SeqList* ps, SLDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->_size; i++)
	{
		if (ps->_a[i] == x)
			return i;
	}
	return -1;
}